package com.prs.crm.dao.oa.impl;

import java.sql.SQLException;
import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.context.Constrains;
import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.oa.WorkSummaryDao;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.oa.WorkSummary;

public class WorkSummaryDaoImpl extends BaseDaoImpl<WorkSummary> implements WorkSummaryDao{

	@Override
	public Collection<WorkSummary> getAllWorkSummary() {
		// TODO Auto-generated method stub
		Criteria criteria = this.getSession().createCriteria(WorkSummary.class);
		return criteria.list();
	}

	@Override
	public Collection<WorkSummary> getWorkSummaryByIds(Collection<Integer> ids) {
		// TODO Auto-generated method stub
		Criteria criteria = this.getSession().createCriteria(WorkSummary.class);
		criteria.add(Restrictions.in("id", ids));
		criteria.addOrder(Order.desc("recordTime"));
		return criteria.list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public Collection<WorkSummary> getAuditWorkSummary(final Person person) {
		// TODO Auto-generated method stub
		return (Collection<WorkSummary>)this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(WorkSummary.class);
				criteria.add(Restrictions.eq("auditPerson", person));
				criteria.add(Restrictions.eq("state", Constrains.TASK_AUDITING));
				criteria.addOrder(Order.desc("recordTime"));				
				return criteria.list();
			}
			
		});
	}

	@Override
	@SuppressWarnings("unchecked")
	public Collection<WorkSummary> getValidCritiqueWorkSummary(final Person person) {
		// TODO Auto-generated method stub
		return (Collection<WorkSummary>) this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(WorkSummary.class);
				criteria.add(Restrictions.eq("state", Constrains.TASK_AUDITING));
				criteria.createAlias("copyToPersons", "c").add(Restrictions.eq("c.id", person.getId()));
				return criteria.list();
			}
			
		});
	}

}
